package com.ruoyi.project.digital.controller;

import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.AuthUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.project.digital.domain.Apply;
import com.ruoyi.project.digital.domain.Payinfo;
import com.ruoyi.project.digital.domain.WechatUser;
import com.ruoyi.project.digital.domain.dto.PayinfoDto;
import com.ruoyi.project.digital.domain.enums.ApplyStatus;
import com.ruoyi.project.digital.domain.enums.IsPay;
import com.ruoyi.project.digital.service.*;
import com.ruoyi.project.system.domain.SysUser;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;

import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 费用支付信息Controller
 *
 * @author ruoyi
 * @date 2020-12-17
 */
@RestController
@RequestMapping("/wechatuser/payinfo")
public class PayinfoController extends BaseController
{
    @Autowired
    private IPayinfoService payinfoService;
    @Autowired
    private IApplyService applyService;
    @Autowired
    private TemplateMsgService templateMsgService;
    @Autowired
    private IWechatUserService wechatUserService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private MiniAppTemplateMsgService miniAppTemplateMsgService;

    /**
     * 查询费用支付信息列表
     */
    @PreAuthorize("@ss.hasPermi('wechatuser:payinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(Payinfo payinfo)
    {
        startPage();
        List<Payinfo> list = payinfoService.selectPayinfoList(payinfo);
        return getDataTable(list);
    }

    /**
     * 导出费用支付信息列表
     */
    @PreAuthorize("@ss.hasPermi('wechatuser:payinfo:export')")
    @Log(title = "费用支付信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Payinfo payinfo)
    {
        List<Payinfo> list = payinfoService.selectPayinfoList(payinfo);
        ExcelUtil<Payinfo> util = new ExcelUtil<Payinfo>(Payinfo.class);
        return util.exportExcel(list, "payinfo");
    }

    /**
     * 获取费用支付信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('wechatuser:payinfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(payinfoService.selectPayinfoById(id));
    }

    /**
     * 新增费用支付信息
     */
    @Log(title = "费用支付信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Payinfo payinfo)
    {

        return toAjax(payinfoService.insertPayinfo(payinfo));
    }

    /**
     * 修改费用支付信息
     */
    @PreAuthorize("@ss.hasPermi('wechatuser:payinfo:edit')")
    @Log(title = "费用支付信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Payinfo payinfo)
    {
        return toAjax(payinfoService.updatePayinfo(payinfo));
    }

    /**
     * 删除费用支付信息
     */
    @PreAuthorize("@ss.hasPermi('wechatuser:payinfo:remove')")
    @Log(title = "费用支付信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(payinfoService.deletePayinfoByIds(ids));
    }

    /**
     * 新增费用支付信息
     */
    @Log(title = "费用支付信息", businessType = BusinessType.INSERT)
    @PostMapping("/insertPayInfo")
    public AjaxResult addPayInfo(@RequestBody PayinfoDto payinfoDto)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        Apply apply = applyService.selectApplyById(payinfoDto.getId());
        if(ObjectUtil.isEmpty(apply)){
           return AjaxResult.error("信息有误，请刷新重试");
        }
        if(!ApplyStatus.PASS.getValue().equals(apply.getStatus())){
            return AjaxResult.error("不是待审核状态，不允许维护打印信息！");
        }
        WechatUser wu = wechatUserService.selectWechatUserById(apply.getUserId());
        //更新申请状态
        apply.setStatus(ApplyStatus.WAIT_PAY.getValue());
        apply.setPrintType(null);
        applyService.updateApply(apply);
        //插入支付数据信息
        Payinfo  payinfo=payinfoService.selectByApplyId(apply.getId());
        if(ObjectUtil.isEmpty(payinfo)){
            payinfo=new Payinfo();
        }
        payinfo.setApplyId(apply.getId());
        payinfo.setIsPay(IsPay.NO_PAY.getValue());
        payinfo.setPrintNum(payinfoDto.getPrintNum());
        payinfo.setPrintAmount(payinfoDto.getPrintAmount());
        payinfo.setFreight(payinfoDto.getFreight());
        payinfo.setTotalAmount(payinfoDto.getTotalAmount());
        payinfo.setUpdateTime(new Date());
        payinfo.setUpdateId(user.getUserId());
        int flag=0;
        //如果apply为空的，则插入，否则更新
        if(ObjectUtil.isNull(payinfo.getId())){
            flag = payinfoService.insertPayinfo(payinfo);
         }else{
            flag = payinfoService.updatePayinfo(payinfo);
        }
        if(flag > 0){
            //待支付提醒 -- 小程序
            miniAppTemplateMsgService.waitPayMsg(apply.getId(),wu.getOpenId(),apply.getApplyNo(),payinfo.getTotalAmount());
        }
        return toAjax(flag);
    }
}
